﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using org.apache.zookeeper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class OZ_ReportAnalytics15_28InterfaceBusiness_2 : OZInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption OZ_Query { get; set; }
        //店铺ID
        public string SellerId { get; set; }
        public OZ_ReportAnalytics15_28InterfaceBusiness_2()
        {
            this.InterfaceName = "分析报告15-28_店铺2";
            //索引字段
            this.MapFields = GetMapField("OZ_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            OZ_Query = this.interfaceOption.Where(x => x.OperateType == "OZ_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LX_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, OZ_NoQueryEventArgs LX_NoQueryEventArgs)
        {
            //API请求是否成功
            LX_NoQueryEventArgs.Success = LX_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {
            try
            {
                //同一个seller_id授权的店铺任取一个sid请求报表数据即可
                //queryEventArgs.CustomData = sellerInterfaceBusiness.Query<Seller>(sellerInterfaceBusiness.LX_Query, SqlDb);
                //设置请求头参数
                var key = JObject.Parse(OZ_Query.TargetLoginData);
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Client-Id", key["Client-Id"].Value<string>());
                headers.Add("Api-Key", key["Api-Key"].Value<string>());
                this.SellerId = key["Client-Id"].Value<string>();
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                queryEventArgs.Page.Total = queryEventArgs.APINodes.Where(x => x.TargetField == "date_from").First().Notes.ToInt();
                queryEventArgs.Page.PageSize = queryEventArgs.APINodes.Where(x => x.TargetField == "limit").First().SourceField.ToInt();
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {
            //获取请求的数据
            OZ_ReqDTO data = new OZ_ReqDTO();
            data.offset = queryEventArgs.Page.PageIndex;
            data.date_to = DateTime.UtcNow.ToString("yyyy-MM-dd");
            data.date_from = DateTime.UtcNow.AddDays(-queryEventArgs.Page.Total).ToString("yyyy-MM-dd");
            queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, OZ_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                ReportAnalyticsDTO result = (ReportAnalyticsDTO)JsonConvert.DeserializeObject<ReportAnalyticsDTO>(queryEventArgs.ResultStr);
                if (result.result.data.Count < queryEventArgs.Page.PageSize)
                {
                    queryEventArgs.Rows = result.result.data;
                    queryEventArgs.Success = true;
                    queryEventArgs.Page.Complete = true;
                }
                else
                {

                    queryEventArgs.Success = true;
                    queryEventArgs.Rows = result.result.data;
                    queryEventArgs.Page.PageIndex += queryEventArgs.Page.PageSize;
                }
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public List<ReportAnalytics> ExecuteInterface()
        {
            List<ReportAnalytics> report = new List<ReportAnalytics>();
            try
            {
                List<OZ_ReportAnalyticsData> data = this.Query<OZ_ReportAnalyticsData>(this.OZ_Query, SqlDb);
                foreach (var item1 in data)
                {
                    ReportAnalytics analytics = new ReportAnalytics();
                    //分组参数
                    analytics.sku = item1.dimensions[0].id;
                    analytics.skuName = item1.dimensions[0].name;
                    analytics.date = item1.dimensions[1].id;
                    analytics.sellerId = this.SellerId;
                    //指标参数
                    analytics.cancellations = item1.metrics[0];
                    analytics.ordered_units = item1.metrics[1];
                    analytics.delivered_units = item1.metrics[2];
                    //analytics.adv_view_pdp = item1.metrics[3];
                    //analytics.adv_view_search_category = item1.metrics[4];
                    //analytics.adv_view_all = item1.metrics[5];
                    //analytics.adv_sum_all = item1.metrics[6];
                    analytics.position_category = item1.metrics[3].IsNullOrEmpty()?"0": item1.metrics[3].ToDouble().ToString("F2");
                    //analytics.postings = item1.metrics[8];
                    //analytics.postings_premium = item1.metrics[9];
                    analytics.id = analytics.sku + analytics.date + analytics.sellerId;
                    report.Add(analytics);
                }


            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
            return report;
        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            var ww = ExecuteInterface();
        }
    }

}
